//
//  LXWebVC.m
//  APMDemo
//
//  Created by Jack on 2020/7/20.
//  Copyright © 2020 LX. All rights reserved.
//

#import "LXWebVC.h"
#import <WebKit/WebKit.h>

@interface LXWebVC ()<WKNavigationDelegate>
/** 加载路径 */
@property (nonatomic, strong) NSURL *url;
/** webview  */
@property (nonatomic, strong) WKWebView *wkWebView;

@end

@implementation LXWebVC

- (id)initWithURL:(NSURL *)url{
    self = [super init];
    if (self) {
        self.url = url;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    //标题
    self.title = [self.url.absoluteString lastPathComponent];
    //界面设置
    [self setupUI];
    //加载链接
    [self loadRequestWithURL:self.url];
}

#pragma mark - 界面设置
- (void)setupUI{
    //背景颜色
    self.view.backgroundColor = [UIColor whiteColor];
    //config
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKPreferences *preferences = [[WKPreferences alloc] init];
    //很重要，如果没有设置这个则不会回调createWebViewWithConfiguration方法，也不会回应window.open()方法
    preferences.javaScriptCanOpenWindowsAutomatically = YES;
    config.preferences = preferences;
    [self loadWKWebViewWithConfig:config];
}

- (void)loadWKWebViewWithConfig:(WKWebViewConfiguration *)config{
    
    //网页
    WKWebView *wkWebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    wkWebView.backgroundColor = [UIColor clearColor];
    wkWebView.navigationDelegate = self;
    [self.view addSubview:wkWebView];
    self.wkWebView = wkWebView;
}

#pragma mark - 加载链接
- (void)loadRequestWithURL:(NSURL *)url{

    if (url && _wkWebView) {
        
        NSURLRequest *request = [NSURLRequest requestWithURL:url
                                                 cachePolicy:NSURLRequestUseProtocolCachePolicy
                                             timeoutInterval:600.0];
        [_wkWebView loadRequest:request];
         
        /*
        if (@available(iOS 9.0,*)) {
            
            NSData *data = [NSData dataWithContentsOfURL:url];
            // 加载二进制文件
            [_wkWebView loadData:data MIMEType:@"text/txt" characterEncodingName:@"UTF-8" baseURL:url];
        }*/
    }
}

#pragma mark - 设置导航按钮
- (void)setupNavigationItem{
    
    UIBarButtonItem *item = nil;
    item = [[UIBarButtonItem alloc] initWithTitle:@"共享"
                                            style:UIBarButtonItemStyleDone
                                           target:self
                                           action:@selector(shareBarButtonItemClicked:)];
    self.navigationItem.rightBarButtonItem = item;
}

#pragma mark - 共享
- (void)shareBarButtonItemClicked:(UIBarButtonItem *)item{
    
    NSURL *url = self.url;
    UIActivityViewController *activityViewController = nil;
    activityViewController = [[UIActivityViewController alloc]initWithActivityItems:@[url]
                                                              applicationActivities:nil];
    //活动行为结束后回调的block
    activityViewController.completionWithItemsHandler = ^(UIActivityType activityType, BOOL completed, NSArray * returnedItems, NSError * __nullable activityError){
        NSLog(@"%@\n%@",activityType,returnedItems);
    };
    [self presentViewController:activityViewController animated:YES completion:nil];
}

#pragma mark - wkWebView代理
// 如果不添加这个，那么wkwebview跳转不了AppStore
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    
    decisionHandler(WKNavigationActionPolicyAllow);
}


- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler
{
    
    decisionHandler(WKNavigationResponsePolicyAllow);
}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler
{
    NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
    completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
}


- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    
}

- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;
{
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
}

@end
